package com.adwin.addcoin.utils

import android.content.Context
import android.content.pm.PackageManager
import android.os.Build
import android.telephony.TelephonyManager
import android.text.TextUtils
import com.adwin.addcoin.AddCoinApplication
import com.google.android.gms.ads.identifier.AdvertisingIdClient
import com.google.android.gms.ads.identifier.AdvertisingIdClient.Info
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch
import kotlin.random.Random


object DevicesUtils {
    val gaidLable:String = "gaid"
    val imei:String = "imei"
    val manufacturerName:String = "manufacturer"
    val device_model = "device_model"
    val packageName = "packageName"
    val versionName = "versionName"
    val language = "language"
    var map = HashMap<String,Any>()
    fun initDevices(mContext:Context){
        val gaid = getGAID(mContext)
        val deviceId = getIMEI(mContext)
        map[gaidLable] = gaid
        map[imei] = deviceId
        map[manufacturerName] = Build.MANUFACTURER?:""
        map[device_model] = Build.MODEL?:""
        map[packageName]=mContext.packageName
        map[versionName] = getVersionName(mContext)?:""
        map[language] = getLocale(mContext)
    }

    private fun getLocale(mContext: Context):String{
        return mContext.resources.configuration.locale.language
    }

    private fun getIMEI(mContext: Context):String{
        if (!TextUtils.isEmpty(AddCoinApplication.gaid))return AddCoinApplication.gaid
        val tm = mContext.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
        try {
            var deviceId = tm.deviceId?:""
            if (deviceId <"0000000000"){
                deviceId = ""
            }
            MainScope().launch(Dispatchers.IO) {
                if (!TextUtils.isEmpty(deviceId)){
                    mContext.dataStore.saveDevicesId(deviceId)
                }
            }
            return deviceId
        }catch (e:Exception){
            return ""
        }
    }

    /**
     * 获取自己应用内部的版本名
     */
    fun getVersionName(context: Context): String? {
        val manager = context.packageManager
        var name: String? = null
        try {
            val info = manager.getPackageInfo(context.packageName, 0)
            name = info.versionName
        } catch (e: PackageManager.NameNotFoundException) {
            e.printStackTrace()
        }
        return name
    }



    private fun getGAID(mContext:Context):String{
        var gaid = ""
        var adInfo:Info? = null;
        try {
            adInfo = AdvertisingIdClient.getAdvertisingIdInfo(mContext)
        }catch (e:Exception){

        }
        if (adInfo != null){
            gaid = adInfo?.id?:""
        }
        return gaid
    }


}